import { Radio } from "antd";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router";
import Chart from "./Chart";
import List from "./List";
import { useAtomValue } from "jotai";
import { isAdminAtom } from "@/store/user";

const tabs = [
  { label: "图示", value: "chart" },
  { label: "列表", value: "list" },
];

export default function Device() {
  const [search, setSearch] = useSearchParams();
  const [tab, setTab] = useState(search.get("view") || "chart");
  const isAdmin = useAtomValue(isAdminAtom);

  useEffect(() => {
    if (!isAdmin) return;
    setSearch((p) => {
      p.set("view", tab);
      return p;
    });
  }, [tab]); // eslint-disable-line

  const _tab = isAdmin ? tab : "chart";

  return (
    <div className="mx-auto flex h-[calc(100vh_-_3rem)] flex-col">
      {isAdmin && (
        <div className="flex flex-none justify-center pt-4">
          <Radio.Group
            options={tabs}
            defaultValue={_tab}
            optionType="button"
            buttonStyle="solid"
            onChange={(e) => setTab(e.target.value)}
          />
        </div>
      )}
      <div className="min-h-0 flex-auto overflow-auto">
        {_tab === "chart" && <Chart />}
        {_tab === "list" && <List />}
      </div>
    </div>
  );
}
